$(function () {
    findById();
});

function findById() {
    let id = sessionStorage.getItem("userId");
    let data = myAjax("/back/user/findById", {id: id}, "get");
    setUserData(data.model);
}

function setUserData(data) {
    $("#username").val(data.username);
    $("#phone").val(data.phone);
    $("#email").val(data.email);
    $("#sex").val(data.username);
    $("input[name='sex'][value=" + data.sex + "]").attr("checked", true);
    // $("#hobby").val(data.hobby);
    setHobby(data.hobby);
    $("#birthday").val(data.birthday.split(" ")[0]);
}

function setHobby(hobby) {
    if (hobby != null) {
        let vals = hobby.split(",");
        $('input:checkbox[name=hobby]').each(function (index, item) {
            for (let i = 0; i < vals.length; i++) {
                if (vals[i] == $(this).val()) {
                    $("input[name='hobby'][value=" + vals[i] + "]").attr("checked", true);
                }
            }
        });
        return vals;
    }
}

function getHobby() {
    let vals = [];
    $('input:checkbox[name=hobby]:checked').each(function (index, item) {
        vals.push($(this).val());
    });
    return vals;
}

function save() {
    let data = {
        username: $("#username").val(),
        phone: $("#phone").val(),
        email: $("#email").val(),
        sex: $('input:radio[name=sex]:checked').val(),
        hobby: getHobby().toString(),
        birthday: $("#birthday").val(),
        id: sessionStorage.getItem("userId")
    };
    let result = myAjax("/back/user/update", data, "post");
    if (result.result == "isHave") {
        alert("当前用户名非常受欢迎，请重新输入");
    }
    if (result.result == 'error') {
        alert("用户名或者密码错误,请重新输入");
    }
    if (result.result == 'success') {
        // findAll();
        closeWindow();
        $(".right").load("/html/back/user/userManage.html");
    }
}